<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<head>
    <link rel="stylesheet" href="${APP_PATH}/static/layui/css/layui.css" type="text/css"/>
    <style type="text/css">
        .layui-input {
            height: 30px;
        }
        /*layui 元素样式改写*/
        .layui-btn-sm{line-height: normal; font-size: 12.5px;}
        .layui-table-view .layui-table-body{min-height: 256px;}
        .layui-table-cell .layui-input.layui-unselect{height: 30px; line-height: 30px;}

        /*设置 layui 表格中单元格内容溢出可见样式*/
        .layui-table-view,
        .layui-table-box,
        .layui-table-body{overflow: visible;}
        .layui-table-cell{height: auto; overflow: visible;}

        /*文本对齐方式*/
        .text-center{text-align: center;}
        /* 使得下拉框与单元格刚好合适 */
        td .layui-form-select{
            margin-top: -5px;
            margin-left: -15px;
            margin-right: -15px;
        }
        .layui-anim-upbit{
            margin-top: -10px;
        }
    </style>
</head>
<script src="${APP_PATH}/static/layui/layui.all.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="yclTransferOrderEdit">
    <form class="layui-form" lay-filter="transferorderForm">
    <blockquote class="layui-elem-quote">
            <div class="layui-fluid">
                <div class="layui-row">
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <div class="layui-form layui-input-inline" lay-filter="typ">
                                <input type="radio" name="typ"  value="3" title="调拨" checked>
                                <input type="radio" name="typ" value="2" title="子库存转移">
                                <input type="radio" name="typ" value="1" title="移位">
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">调出厂区</label>
                            <div class="layui-form layui-input-inline" lay-filter="fromAreaCode">
                                <select id="fromAreaCode" lay-filter="fromAreaCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in arealist" :value="item.id" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm4">
                        <div class="layui-inline">
                            <label style="width: 65px">调出仓库</label>
                            <div class="layui-form layui-input-inline" lay-filter="fromStoreCode">
                                <select id="fromStoreCode" lay-filter="fromStoreCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in fromStorelist" :value="item.code" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="layui-row" style="margin-top: 10px;">
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">调入厂区</label>
                            <div class="layui-form layui-input-inline" lay-filter="toAreaCode">
                                <select id="toAreaCode" lay-filter="toAreaCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in arealist" :value="item.id" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">调入仓库</label>
                            <div class="layui-form layui-input-inline" lay-filter="toStoreCode">
                                <select id="toStoreCode" lay-filter="toStoreCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in toStorelist" :value="item.code" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <label style="width: 65px">部门</label>
                            <div class="layui-form layui-input-inline" lay-filter="plantDept">
                                <select id="plantDept" lay-filter="plantDept" lay-search="">
                                    <option value="">请选择</option>
                                    <option v-for="(item,index) in plantDeptlist" :value="item.code" :key="index">{{item.text}}</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-sm3">
                        <div class="layui-inline">
                            <button id="submitSave" type="button" @click="submitTransfer" class="layui-btn layui-btn-sm">
                                <i class="layui-icon">&#xe605;</i>提交
                            </button>
                        </div>
                        <div class="layui-inline">
                        </div>
                    </div>
                </div>
            </div>
    </blockquote>
    <div id="toolbar">
        <div style="margin-left: 15px;">
            <button type="button" @click="delLine" class="layui-btn layui-btn-sm layui-btn-danger">
                <i class="layui-icon">&#xe640;</i>清除
            </button>
            <button type="button" @click="addLine" class="layui-btn layui-btn-sm layui-btn-normal">
                <i class="layui-icon">&#xe654;</i>添加
            </button>
        </div>
    </div>

    <table id="tableGridCheckEdit"></table>

    </form>
</div>

<script>
    const context_path = '${APP_PATH}';
    const form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        table = layui.table,
        $ = layui.jquery;
    var tableIns;
    let vm = new Vue({
        el: '#yclTransferOrderEdit',
        data: {
            tbData: [],
            selectHtml:[],
            arealist:[],
            fromStorelist:[],
            toStorelist:[],
            plantDeptlist:[],
            materialCodelist:[],
            params: {
                fromAreaCode: "",
                fromStoreCode: "",
                toAreaCode:'',
                toStoreCode:'',
                line: []
            }
        },
        methods: {
            delLine(){
                var selectData = layui.table.checkStatus('tableGridCheckEdit').data;
                this.tbData = table.cache['tableGridCheckEdit'];
                for(var i = 0; i < this.tbData.length; i++){
                    if(this.tbData[i].tempId === selectData[0].tempId){
                        this.tbData.splice(i,1);
                    }
                }
                tableIns.reload({
                    data : this.tbData
                });
            },
            addLine(){
                if (!this.formVerify())
                {
                    return;
                }
                this.tbData = table.cache['tableGridCheckEdit'];
                let newRow = {tempId: new Date().valueOf(), state: 0};
                this.tbData.push(newRow);
                tableIns.reload({
                    data : this.tbData
                });
            },
            submitTransfer() {
                let typ = $('input[name="typ"]:checked').val();
                if (typ == 3 && $('#fromAreaCode').val() == $('#toAreaCode').val())
                {
                    layer.alert('调拨须选择不同的厂区组织!');
                    return false;
                }
                if (typ == 2 && ($('#fromAreaCode').val() != $('#toAreaCode').val() || $('#fromStoreCode').val() == $('#toStoreCode').val()))
                {
                    layer.alert('子库存转移须选择相同厂区的不同仓库!');
                    return false;
                }
                if (typ == 1 && ($('#fromStoreCode').val() != $('#toStoreCode').val()||
                    $('#fromAreaCode').val() != $('#toAreaCode').val()&&$('#fromStoreCode').val() == $('#toStoreCode').val()))
                {
                    layer.alert('移位须选择相同的厂区和仓库!');
                    return false;
                }
                if (typ == 2 && $('#plantDept').val() == '')
                {
                    layer.alert('子库存转移须选择部门!');
                    return false;
                }
                if (!this.formVerify())
                {
                    return;
                }

                this.params.line = table.cache['tableGridCheckEdit']
                if (this.params.line.length==0)
                {
                    layer.alert('请添加物料信息!');
                    return false;
                }
                if (this.params.line.some(m=> m.outQuantity==null||m.outQuantity==''||isNaN(m.outQuantity)))
                {
                    layer.alert('移出数量非数字!');
                    return;
                }
                let tempData = [];
                this.params.line.forEach(m=>{
                    let tmp = tempData.find(x=>x.materialCode==m.materialCode && x.fromLocator==m.fromLocator && x.lotsNum==m.lotsNum);
                    if (tmp!=undefined){
                        tmp.outQuantity=Number(tmp.outQuantity)+Number(m.outQuantity)
                    }
                    else {
                        let newRow = {}
                        newRow.materialCode=m.materialCode
                        newRow.fromLocator=m.fromLocator
                        newRow.lotsNum=m.lotsNum
                        newRow.quality=m.quality
                        newRow.outQuantity=m.outQuantity
                        tempData.push(newRow)
                    }
                })
                if (tempData.some(m=> m.quality<m.outQuantity))
                {
                    layer.alert('移出数量不能大于库存数量!');
                    return;
                }
                this.params.tranType=typ
                this.params.status=0

                $('#submitSave').addClass('layui-btn-disabled');
                $('#submitSave').attr('disabled', 'disabled');
                $.ajax({
                    type: 'POST',
                    url: context_path + "/ycl/insidewarehouse/transferOrder/save",
                    contentType: "application/json",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(this.params),
                    success: function (res) {
                        $('#submitSave').removeClass('layui-btn-disabled');
                        $('#submitSave').removeAttr('disabled');
                        window.parent.tableRender()
                        let index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    }
                })
            },
            /*校验*/
            formVerify(){
                this.params.fromAreaCode = $('#fromAreaCode').val();
                this.params.fromStoreCode = $('#fromStoreCode').val();
                this.params.toAreaCode = $('#toAreaCode').val();
                this.params.toStoreCode = $('#toStoreCode').val();
                this.params.dept = $('#plantDept').val();
                if (this.params.fromAreaCode=='')
                {
                    layer.alert('请选择调出厂区!');
                    return false;
                }
                if (this.params.fromStoreCode=='')
                {
                    layer.alert('请选择调出仓库!');
                    return false;
                }
                if (this.params.toAreaCode=='')
                {
                    layer.alert('请选择调入厂区!');
                    return false;
                }
                if (this.params.toStoreCode=='')
                {
                    layer.alert('请选择调入仓库!');
                    return false;
                }
                return true;
            },
            initDate(){
                var url = window.location.href;
                var dz_url = url.split('id=')
                if (dz_url.length>1)
                {
                    $("#fromAreaCode").each(function() {
                        $(this).children("option").each(function() {
                            // 判断需要对那个选项进行回显
                            if (this.value == '92') {
                                $(this).attr("selected","selected");
                            }
                        });
                        form.render('select','fromAreaCode');
                        $.ajax({
                            url:context_path + '/warehouselist/getYclWarehouseByFactory',
                            type:'post',
                            data:{factoryCode:92},
                            success:function(res){
                                vm.fromStorelist = res.wareHouseList;
                                vm.$nextTick(() => {
                                    form.render('select','fromStoreCode');
                                    $("#fromStoreCode").each(function() {
                                        $(this).children("option").each(function() {
                                            // 判断需要对那个选项进行回显
                                            if (this.value == '981') {
                                                $(this).attr("selected","selected");
                                            }
                                        });
                                        form.render('select','fromStoreCode');
                                    })
                                })
                            }
                        });
                    })
                }
            },
            renderSelectOptions: function(e){
                let html = [];
                html.push('<div class="layui-form" lay-filter="materialCode">');
                html.push('<select name="materialCode" id="materialCode" data-value="'+e.tempId+'" lay-filter="materialCode" lay-search="">');
                html.push('<option value="">请选择</option>');
                this.materialCodelist.forEach(m=>{
                    html.push('<option value="');
                    html.push(m.materialCode);
                    html.push('_');
                    html.push(m.locatorCode);
                    html.push('"');
                    if(m.materialCode == e.materialCode ){
                        html.push(' selected="selected"');
                    }
                    html.push('>');
                    html.push(m.materialCode+"("+m.materialName+")");
                    html.push('</option>');
                })
                html.push('</select></div>');
                return html.join('');
            }
        },
        created() {
            $.get(context_path + '/ycl/baseinfo/basedata/area/0'
                , res=> {
                    this.arealist = res.data;
                    this.$nextTick(() => {
                        form.render('select','fromAreaCode');
                        form.render('select','toAreaCode');
                        form.render('select','plantDept');
                        this.initDate();
                    });
                })
            $.get(context_path + '/ycl/baseinfo/plant/selectPlant/999'
                , res=> {
                    this.plantDeptlist = res.data;
                    this.$nextTick(() => {
                        form.render('select','plantDept');
                    });
                })
        },
        mounted() {
            form.render();
            tableIns = table.render({
                elem: '#tableGridCheckEdit'
                ,data: this.tbData
                ,size: 'sm'
                ,cols: [[
                    {type: 'checkbox'}
                    ,{field: 'tempId', hide: true}
                    ,{field: 'materialCode', width:'150', title: '物料编码', templet: (d)=>vm.renderSelectOptions(d)}
                    ,{field: 'materialName', width:'300', title: '物料名称', style:'overflow:hidden'}
                    ,{field: 'lotsNum', width:'150', title: '批次号'}
                    ,{field: 'fromLocator', width:'100', title: '所在库位'}
                    ,{field: 'quality', width:'100', title: '库存数量'}
                    ,{field: 'primaryUnit', width:'80', title: '单位'}
                    ,{field: 'outQuantity', width:'100', style:'background-color: #5fb878;color:#fff', title: '移出数量', edit: 'text'}
                ]],
                done: function(res, curr, count){
                    this.tbData = res.data;
                }
            });
        }
    })

    //监听select
    form.on('select(fromAreaCode)', function (data) {
        $.get(context_path + '/ycl/baseinfo/basedata/store/'+data.value
            , res=> {
                vm.fromStorelist = res.data;
                vm.$nextTick(() => {
                    form.render('select','fromStoreCode');
                })
            })
        let typ = $('input[name="typ"]:checked').val();
        if (typ == 2 || typ == 1) {
            $("#toAreaCode").each(function () {
                $(this).children("option").each(function () {
                    if (this.value == data.value) {
                        $(this).attr("selected", "selected");
                    }
                });
                form.render('select', 'toAreaCode');
                $.get(context_path + '/ycl/baseinfo/basedata/store/'+data.value
                    , res=> {
                        vm.toStorelist = res.data;
                        vm.$nextTick(() => {
                            form.render('select','toStoreCode');
                        })
                    })
            })
        }
    });
    //监听select
    form.on('select(toAreaCode)', function (data) {
        $.get(context_path + '/ycl/baseinfo/basedata/store/'+data.value
            , res=> {
                vm.toStorelist = res.data;
                vm.$nextTick(() => {
                    form.render('select','toStoreCode');
                })
            })
    });
    form.on('select(plantDept)', function (data) {
        $.get(context_path + '/ycl/baseinfo/plant/selectPlant'
            , res=> {
                vm.plantDeptlist = res.data;
                vm.$nextTick(() => {
                    form.render('select','plantDept');
                })
            })
    });
    //监听select
    form.on('select(fromStoreCode)', function (data) {
        $.get(context_path + '/ycl/report/inventory/listView', {
            //areaCode : $('#fromAreaCode').val(),
            storeCode: data.value
        }, function (res) {
            vm.materialCodelist = res.data;
        })
        let typ = $('input[name="typ"]:checked').val();
        if (typ == 1) {
            $("#toStoreCode").each(function () {
                $(this).children("option").each(function () {
                    if (this.value == data.value) {
                        $(this).attr("selected", "selected");
                    }
                });
                form.render('select', 'toStoreCode');
            })
        }
    });
    //监听select
    form.on('select(materialCode)', function (data) {
        var elem = data.othis.parents('tr');
        var id = elem.first().find('td').eq(1).text();
        let val = data.value.split('_')
        $.get(context_path + '/ycl/report/inventory/listView', {
            storeCode:$('#fromStoreCode').val(),
            materialCode: val[0],
            locatorCode:val[1]
        }, function (res) {
            this.tbData = table.cache['tableGridCheckEdit'];
            res.data.forEach(m=>{
                this.tbData.forEach(n=>{
                    if (n.tempId==id)
                    {
                        n.materialCode = m.materialCode;
                        n.materialName = m.materialName;
                        n.fromLocator = m.locatorCode;
                        n.primaryUnit = m.primaryUnit;
                        n.lotsNum = m.lotsNum;
                        n.quality = m.quality;
                    }
                })
            })
            tableIns.reload({
                data : this.tbData
            });
        })
    });

    // var upload = layui.upload;
    // var form = layui.form;
    // //此处即为 radio 的监听事件
    // form.on('radio(levelM)', function(data){
    //     console.log(data.elem); //得到radio原始DOM对象
    //     console.log(data.value); //被点击的radio的value值
    //     var level = data.value;//被点击的radio的value值
    //     $(".sel-parent-msg").hide();
    //     $(".sel-parent-msg-"+level).show();
    // });
    // });

</script>
